package com.netted.operationassistant.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.hardware.Camera;
import android.os.Bundle;
import android.os.Handler;
import android.util.Base64;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.netted.operationassistant.R;
import com.netted.operationassistant.camera.CameraPreview;
import com.netted.operationassistant.camera.CameraView;
import com.netted.operationassistant.constant.Constant;
import com.netted.operationassistant.utils.FaceView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

public class CameraActivity extends BaseActivity {
    private Camera mCamera;
    private CameraPreview mPreview;
    private TextView camera_tv;
    private Handler handler = null;
    private String secondText = "3";
    private String from;
    private int sensorBright = 0;
    private CameraView cameraView;
    private FaceView faceView;
    Bitmap fullBitmap;

    private ImageView faceImgView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_camera);
        try{
            from = getIntent().getStringExtra("from");
            if (from == null || "".equals(from)){
                this.finish();
            }
            mCamera = getCameraInstance();//上面有方法内容
            camera_tv = (TextView)findViewById(R.id.camera_tv);
            if (mPreview == null){
                mPreview = new CameraPreview(this, mCamera);
            }
            FrameLayout preview = (FrameLayout) findViewById(R.id.camera_preview);
            preview.addView(mPreview);
            handler = new Handler();
            new Thread(new Runnable() {
                @Override
                public void run() {
                    autoTakePhoto();
                }
            }).start();
        }catch (Exception e){
            e.printStackTrace();
            ToastUtils.showLong(e.getMessage());
        }

/*
        try{
            initView();
        }catch (Exception e){
            showDialog("异常",e.getMessage(),null);

        }
*/
    }


    /*private void initView() {
        cameraView = (CameraView) findViewById(R.id.camera_view);
        faceView = (FaceView) findViewById(R.id.face_view);
        faceImgView = (ImageView) findViewById(R.id.face_img);
        cameraView.setFaceView(faceView);
        cameraView.setOnFaceDetectedListener(new CameraView.OnFaceDetectedListener() {
            @Override
            public void onFaceDetected(Bitmap bm) {
                //检测到人脸后的回调方法
                fullBitmap = bm;
                faceImgView.setImageBitmap(fullBitmap);
            }
        });
    }*/

    private void showDialog() {
        LogUtils.e("人脸区域亮度：" + getBright(fullBitmap) + "\n整幅图片亮度：" + getBright(fullBitmap) + "\n光线传感器的值：" + sensorBright);
    }

    public int getBright(Bitmap bm) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        int r, g, b;
        int count = 0;
        int bright = 0;
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                count++;
                int localTemp = bm.getPixel(i, j);
                r = (localTemp | 0xff00ffff) >> 16 & 0x00ff;
                g = (localTemp | 0xffff00ff) >> 8 & 0x0000ff;
                b = (localTemp | 0xffffff00) & 0x0000ff;
                bright = (int) (bright + 0.299 * r + 0.587 * g + 0.114 * b);
            }
        }
        return bright / count;
    }


    @Override
    protected void onStop() {
        super.onStop();
        if (mCamera != null) {
            mCamera.stopPreview();
            mCamera.release();
            mCamera = null;
        }

    }

    public void autoTakePhoto() {
        int second = 2;
        try {
            while (second > -1) {
                handler.post(runnableUi);
                secondText = second + "";
                second--;
                Thread.sleep(1200);
            }
            takePhoto();
        } catch (Exception e) {
            e.printStackTrace();
        }
       /* try{
            Thread.sleep(10200);
            camera_tv.setText(second + "111");
        }catch (Exception e){

        }*/

    }

    // 构建Runnable对象，在runnable中更新界面
    Runnable runnableUi = new Runnable() {
        @Override
        public void run() {
            //更新界面
            camera_tv.setText(secondText);
        }

    };


    public void takePhoto() {
        mCamera.takePicture(null, null, new Camera.PictureCallback() {
            @Override
            public void onPictureTaken(byte[] data, Camera camera) {
                Bitmap bmp = BitmapFactory.decodeByteArray(data, 0, data.length);//把图片转化成字节数据...
                String base64 = bitmapToBase64(bmp);
                String catbinetId = sharedPreferencesHelper.getSharedPreference(Constant.XML_SCHOOL_ID, "") + "";
                String code = sharedPreferencesHelper.getSharedPreference(Constant.XML_CATBINET_CODE, "") + "";
                String groupId = catbinetId + "_" + code;
                Intent intent = null;
                if (from.equals("GetDeviceActivity")) {
                    intent = new Intent(CameraActivity.this, GetDeviceActivity.class);
                }else if (from.equals("ChargeActivity")){
                    intent = new Intent(CameraActivity.this, ChargeActivity.class);
                    Constant.param1 = "CameraActivity";
                    Constant.param2 = base64;
                    Constant.param3 = groupId;
                }else if (from.equals("GetDevice2Activity")){
                    intent = new Intent(CameraActivity.this, GetDevice2Activity.class);
                    Constant.param1 = "CameraActivity";
                    Constant.param2 = base64;
                    Constant.param3 = groupId;
                }else if (from.equals("Charge2Activity")){
                    intent = new Intent(CameraActivity.this, Charge2Activity.class);
                    Constant.param1 = "CameraActivity";
                    Constant.param2 = base64;
                    Constant.param3 = groupId;
                }





                intent.putExtra("groupId", groupId);
                intent.putExtra("from", "CameraActivity");
                intent.putExtra("base64", base64);
                mCamera.stopPreview();
                mCamera.release();
                mCamera = null;
                startActivity(intent);
                CameraActivity.this.finish();
            }
        });
    }


    public static Camera getCameraInstance() {
        Camera c = null;
        try {
            c = Camera.open(0); // attempt to get a Camera instance
        } catch (Exception e) {
            e.printStackTrace();
            LogUtils.e("getCameraInstance Exception===============" + e.getMessage());
        }
        return c; // returns null if camera is unavailable
    }

    @SuppressLint("NewApi")
    public static String bitmapToBase64(Bitmap bitmap) {

        // 要返回的字符串
        String reslut = null;

        ByteArrayOutputStream baos = null;

        try {

            if (bitmap != null) {

                baos = new ByteArrayOutputStream();
                /**
                 * 压缩只对保存有效果bitmap还是原来的大小
                 */
                bitmap.compress(Bitmap.CompressFormat.JPEG, 30, baos);

                baos.flush();
                baos.close();
                // 转换为字节数组
                byte[] byteArray = baos.toByteArray();

                // 转换为字符串
                reslut = Base64.encodeToString(byteArray, Base64.DEFAULT);
            } else {
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {

            try {
                if (baos != null) {
                    baos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
        return reslut;

    }
}
